package com.foton.logistic.activity;


import android.Manifest;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Configuration;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.v4.app.FragmentTabHost;
import android.view.View;
import android.widget.TabHost.TabSpec;
import android.widget.TextView;

import com.baidu.android.pushservice.PushConstants;
import com.baidu.android.pushservice.PushManager;
import com.foton.logistic.R;
import com.foton.logistic.base.BaseFragmentActivity;
import com.foton.logistic.daemon.IntentWrapper;
import com.foton.logistic.fragment.HomeFragment;
import com.foton.logistic.fragment.OrderListFragment;
import com.foton.logistic.fragment.PersonalCenterFragment;
import com.foton.logistic.listener.IOnResultListener;
import com.foton.logistic.task.DispatchTask;
import com.foton.logistic.task.ShowDialogTask;
import com.foton.logistic.task.TaskConstant;
import com.foton.logistic.util.BaseConstant;
import com.foton.logistic.util.OptionUtil;
import com.foton.logistic.util.PermissionUtil;
import com.foton.logistic.util.SharedUtil;
import com.foton.logistic.util.VersionCheckUtil;
import com.foton.logistic.util.net.HttpUtil;
import com.foton.logistic.util.tool.LogUtil;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import butterknife.InjectView;
import butterknife.OnClick;
import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.OnNeverAskAgain;
import permissions.dispatcher.OnPermissionDenied;
import permissions.dispatcher.OnShowRationale;
import permissions.dispatcher.PermissionRequest;
import permissions.dispatcher.RuntimePermissions;


@RuntimePermissions
public class HomeActivity extends BaseFragmentActivity {
    @InjectView(android.R.id.tabhost)
    public FragmentTabHost mTabHost;
    @InjectView(R.id.base_ui_home_radio0)
    public TextView naviText0;
    @InjectView(R.id.base_ui_home_radio1)
    public TextView naviText1;
    @InjectView(R.id.base_ui_home_radio2)
    public TextView naviText2;
    public int tabFlag = 0;
    private ReceiveBroadcast receiveBroadcast;

    private final Class[] fragments = { HomeFragment.class, OrderListFragment.class,
            PersonalCenterFragment.class };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if ((getIntent().getFlags() & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != 0) {
            finish();
            return;
        }
        setTaskTag(getClass().getSimpleName());
        setContentView(R.layout.base_ui_home);
    }


    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
    }

    @Override
    protected void onDestroy(){

        try {
//            PushManager.stopWork(this);
//            BaseApplication.self().stopLocation();
            unregisterReceiver(receiveBroadcast);
        }catch (Exception e){
            e.printStackTrace();
        }
        super.onDestroy();

    }

    @Override
    public void init(){
        PermissionUtil.doACacheNeedsPermissionWithCheck(this);

//        if (StringUtil.isEmpty(SharedUtil.getUserId(getApplicationContext()))) {
//            Intent intent = new Intent(this, LoginActivity.class);
//            startActivity(intent);
////            stop();
//            finishSelf();
//            return;
//        }

        registerBroadcast();
        mTabHost.setup(this, getSupportFragmentManager(), R.id.base_ui_home_frame);
        int count = fragments.length;
        for (int i = 0; i < count; i++) {
			/* 为每一个Tab按钮设置图标、文字和内容 */
            TabSpec tabSpec = mTabHost.newTabSpec(i + "").setIndicator(i + "");
			/* 将Tab按钮添加进Tab选项卡中 */
            mTabHost.addTab(tabSpec, fragments[i], null);
        }
        setCurrentScreen(0);
        mTabHost.setCurrentTab(0);
        VersionCheckUtil versionCheckUtils = new VersionCheckUtil(this,naviText0,taskTag);
        versionCheckUtils.checkVersion(false);
        //autoBindBaiduYunTuiSong();

//        if (BaseConstant.IS_KEEP_LIVE){
//            IntentWrapper.whiteListMatters(this, "轨迹跟踪服务的持续运行");
//        }
    }

    @Override
    public void onNewIntent(Intent intent){
        super.onNewIntent(intent);
        int index = intent.getIntExtra(BaseConstant.INTENT_TYPE,0);
        setCurrentScreen(index);
    }

    @OnClick({R.id.base_ui_home_radio0,R.id.base_ui_home_radio1,R.id.base_ui_home_radio2})
    public void onNaviSelected(View view){
        switch (view.getId()){
            case R.id.base_ui_home_radio0:
                setCurrentScreen(0);
                tabFlag = 0;
                break;
            case R.id.base_ui_home_radio1:
                setCurrentScreen(1);
                tabFlag = 1;
                break;
            case R.id.base_ui_home_radio2:
                setCurrentScreen(2);
                tabFlag = 2;
//                Bundle bundle = new Bundle();
//                bundle.putString(BaseConstant.INTENT_ID, "1");
//                Intent intent = new Intent(this, UploadAbnormalActivity.class);
//                intent.putExtras(bundle);
//                startActivity(intent);
                break;
            default:
                break;
        }
    }

    private void setCurrentScreen(int index){
        mTabHost.setCurrentTab(index);
        naviText0.setSelected(false);
        naviText1.setSelected(false);
        naviText2.setSelected(false);
        switch (index){
            case 0:
                naviText0.setSelected(true);
                break;
            case 1:
                naviText1.setSelected(true);
                break;
            case 2:
                naviText2.setSelected(true);
                break;
            default:
                break;
        }
    }

    private void autoBindBaiduYunTuiSong()
    {
        PushManager.startWork(getApplicationContext(), PushConstants.LOGIN_TYPE_API_KEY, "3Sb7qtrnahdxCuOewWVKXBGU");
        List<String> tags = new ArrayList<String>();
        tags.add(""+SharedUtil.getUserId(this));
        PushManager.setTags(getApplicationContext(), tags);
    }



    private void registerBroadcast(){
        if (receiveBroadcast ==null){
            receiveBroadcast = new ReceiveBroadcast();
            IntentFilter filter = new IntentFilter();
            filter.addAction(BaseConstant.ACTION_HOME);
            filter.addAction(BaseConstant.ACTION_PUSH);
            registerReceiver(receiveBroadcast, filter);
        }
    }

    @NeedsPermission({Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE})
    void checkPhoto() {
    }


    public class ReceiveBroadcast extends BroadcastReceiver
    {
        @Override
        public void onReceive(Context context, Intent intent)
        {
            try {
                String action = intent.getAction();
                if (action.equals(BaseConstant.ACTION_HOME)){
                    final int type = intent.getExtras().getInt(BaseConstant.INTENT_TYPE);
                    new Handler().postDelayed(new Runnable()
                    {
                        public void run()
                        {
                            setCurrentScreen(type);
                        }
                    }, 50);
                }else if (intent.getAction().equals(BaseConstant.ACTION_PUSH)) {
                    //接收推送绑定成功
                    String userId = intent.getStringExtra(BaseConstant.INTENT_ARG);
                    String channelId = intent.getStringExtra(BaseConstant.INTENT_CONTENT);
                    LogUtil.e("channelId= "+channelId);
                    //setPush(false, userId, channelId);
                }
            }catch (Exception e){
                e.printStackTrace();
            }

        }
    }


    public void setPush(boolean showDialog, String userId, String channelId) {
        if (SharedUtil.getPushSet(this)) {
            return;
        }
        Map<String, Object> argMap = HttpUtil.getEncryMap(this);
        argMap.put("pushId", userId);
        argMap.put("channelId", channelId);
        argMap.put("terminalId", "0");
        ShowDialogTask task = new ShowDialogTask(this, taskTag, containLayout, getString(R.string.task3), showDialog, BaseConstant.setPush, argMap, TaskConstant.POST);
        task.setiOnResultListener(new IOnResultListener() {
            @Override
            public void onOK(DispatchTask task) {
                SharedUtil.savePushSet(HomeActivity.this, true);
            }

            @Override
            public void onError(DispatchTask task) {

            }

            @Override
            public void onDone(DispatchTask task) {

            }
        });
        task.execute();
    }

    @NeedsPermission(Manifest.permission.ACCESS_FINE_LOCATION)
    @Override
    public void doACacheNeedsPermission() {

    }

    @OnShowRationale(Manifest.permission.ACCESS_FINE_LOCATION)
    @Override
    public void ACacheShowRationale(PermissionRequest request) {
        request.proceed(); // 提示用户权限使用的对话框
    }

    @OnPermissionDenied(Manifest.permission.ACCESS_FINE_LOCATION)
    @Override
    public void ACacheOnPermissionDenied() {
        new Handler().postDelayed(new Runnable() {
            public void run() {
                PermissionUtil.showPermissionDialog(HomeActivity.this, naviText0);
            }
        }, 1000);
    }

    @OnNeverAskAgain(Manifest.permission.ACCESS_FINE_LOCATION)
    @Override
    public void ACacheOnNeverAskAgain() {
        new Handler().postDelayed(new Runnable() {
            public void run() {
                PermissionUtil.showPermissionDialog(HomeActivity.this, naviText0);
            }
        }, 1000);
    }

    /**
     * 权限请求回调，提示用户之后，用户点击“允许”或者“拒绝”之后调用此方法
     * @param requestCode  定义的权限编码
     * @param permissions 权限名称
     * @param grantResults 允许/拒绝
     */
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        PermissionUtil.onRequestPermissionsResult(this, requestCode, grantResults);
        HomeActivityPermissionsDispatcher.onRequestPermissionsResult(this, requestCode, grantResults);
    }

    long firstTime = 0;

    @Override
    public void onBackPressed() {
        try {
            //防止华为机型未加入白名单时按返回键回到桌面再锁屏后几秒钟进程被杀
            if (BaseConstant.IS_KEEP_LIVE){
                IntentWrapper.onBackPressed(this);
            }else {
            long secondTime = System.currentTimeMillis();
            if (secondTime - firstTime > 2000) {
                OptionUtil.addToast(this, getString(R.string.quit));
                firstTime = secondTime;
            } else {
                finishSelf();
            }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
